/**
 * 设置cookie - setCookie(option)
 * @param {Object}   option                   参数
 * @param {String}   option -- key            键
 * @param {String}   option -- value          值
 * @param {Number}   option -- expireDays     过期时间
 * @param {Number}   option -- domain         域
 * @param {Number}   option -- routing        路径
 */
interface CookieType {
    key: string
    value: string
    expireDays?: number
    domain?: string
    routing?: string
}
export const setCookie = function (option: CookieType) {
    let optionDefault: CookieType = {
        key: '',
        value: '',
        expireDays: 1,
        domain: '',
        routing: '/',
    }
    optionDefault = { ...option }
    const exdate = new Date()
    let cookie
    cookie = `${optionDefault.key}=${encodeURIComponent(optionDefault.value)}`
    optionDefault.domain && (cookie += `; domain=${optionDefault.domain}`)
    optionDefault.routing && (cookie += `; routing=${optionDefault.routing}`)
    optionDefault.expireDays && exdate.setDate(exdate.getDate() + optionDefault.expireDays);
    optionDefault.expireDays && (cookie += `; expires=${exdate}`)
    console.log('cookie', cookie)
    document.cookie = cookie
}

/**
 * 获取cookie - getCookie(key)
 * @param  {Object}   key                 键
 * @result {*}        result              返回cookie值，没有就返回空
 */
export const getCookie = function (key: string) {
    const _cookie = document.cookie
    const itemsArr = _cookie.split('; ')
    let item = []
    for (let i = 0; i < itemsArr.length; i++) {
        item = itemsArr[i].split('=')
        if (key === item[0] && item.length === 2) {
            return decodeURIComponent(item[1])
        }
    }
    return ''
}

/**
 * 删除cookie - removeCookie(key)
 * @param  {Object}   key                 键
 */
export const removeCookie = function (key: string) {
    const date = new Date()
    date.setDate(date.getDate() - 10000 * 3600 * 31)
    document.cookie = `${key}=;expires = ${date.toString()}`
}

